package com.efounder.chat.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.struct.MessageChildTypeConstant;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.JFStringUtil;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;

import static com.efounder.chat.fragment.ChatSenderFragment.chatpath;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 网址图片发送消息编辑页面
 *
 * @author YQS
 */
public class NotificationMessageEditActivity extends BaseActivity implements View.OnClickListener {

    private StubObject mStubObject;
    private Hashtable mHashtable;
    private String mToUserId;
    private Bundle mBundle;
    private String chatType;

    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvSend;

    //    private EditText etImageTitle;
//    private EditText etImageUrl;
//    private EditText etWebTitle;
//    private EditText etWebUrl;
    private Button butEnter;

    private TextView tvImageSelectTip;
    private ImageView ivTopIcon;
    private EditText etTopTitle;
    private EditText etBottomTitle;
    private EditText etWebUrl;

    //本地文件路径
    private String localImagePath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_notification_message);

        mBundle = getIntent().getExtras();
        mStubObject = (StubObject) mBundle.getSerializable("stubObject");
        mHashtable = mStubObject.getStubTable();
        mToUserId = (String) mHashtable.get("toUserId");
        chatType = (String) mHashtable.get("chatType");
        initView();

    }


    private void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvSend = (TextView) findViewById(R.id.tv_save);
        // tvSend.setVisibility(View.VISIBLE);
        tvTitle.setText(ResStringUtil.getString(R.string.wrchatview_notice));
//        etImageTitle = (EditText) findViewById(R.id.et_image_title);
//        etImageUrl = (EditText) findViewById(R.id.et_image_url);
//        etWebTitle = (EditText) findViewById(R.id.et_web_title);
        tvImageSelectTip = (TextView) findViewById(R.id.tv_image_select_tip);
        ivTopIcon = (ImageView) findViewById(R.id.iv_top_icon);
        etTopTitle = (EditText) findViewById(R.id.tv_top_title);
        etBottomTitle = (EditText) findViewById(R.id.tv_bottom_title);
        etWebUrl = (EditText) findViewById(R.id.et_web_url);
//        etWebUrl = (EditText) findViewById(R.id.et_web_url);
        butEnter = (Button) findViewById(R.id.but_enter);


        ivTopIcon.setOnClickListener(this);
        butEnter.setOnClickListener(this);
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm.getText() != null) {
            //剪贴板有内容，判断是否是网址，加载webView
            String text = cm.getText().toString();
            if (JFStringUtil.isHttpUrl(text)) {
                ToastUtil.showToast(this, ResStringUtil.getString(R.string.wrchatview_read_url));
                etWebUrl.setText(text);
            }
        }


    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_save) {
            checkMessage();
        } else if (id == R.id.but_enter) {
            checkMessage();
        } else if (id == R.id.iv_top_icon) {
            Intent intent = new Intent(NotificationMessageEditActivity.this, JFPicturePickPhotoWallActivity.class);

            intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 1);//可选择的最大照片数
            intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, false);
            startActivityForResult(intent, 40);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 40 && resultCode == RESULT_OK) {
            //图库选择照片
            ArrayList<String> arrayList = (ArrayList<String>) data.getExtras().get("mSelectedPics");
            if (arrayList == null) {
                return;
            }
            if (arrayList.size() == 0) {
                return;
            }
            localImagePath = arrayList.get(0);
            tvImageSelectTip.setVisibility(View.GONE);
            LXGlideImageLoader.getInstance().displayImage(this, ivTopIcon, arrayList.get(0));
        }
    }

    private void checkMessage() {

        final String iamgeTitle = etTopTitle.getText().toString();
        final String webUrl = etWebUrl.getText().toString();
        final String webTitle = etBottomTitle.getText().toString();
        if ("".equals(iamgeTitle.trim())) {
            ToastUtil.showToast(this, ResStringUtil.getString(R .string.wrchatview_image_title_not_null));
            return;
        }
        if (localImagePath == null || "".equals(localImagePath)) {
            ToastUtil.showToast(this, ResStringUtil.getString(R.string.wrchatview_image_not_null));
            return;
        }
        if ("".equals(webTitle.trim())) {
            ToastUtil.showToast(this, ResStringUtil.getString(R.string.wrchatview_url_title_not_null));
            return;
        }
        if ("".equals(webUrl.trim())) {
            ToastUtil.showToast(this, ResStringUtil.getString(R.string.wrchatview_url_not_null));
            return;
        }

        if (!JFStringUtil.isHttpUrl(webUrl)) {
            ToastUtil.showToast(this, ResStringUtil.getString(R.string.wrchatview_please_enter_legitimate_url));
            return;
        }
        //压缩图片

        String img = localImagePath;
        if (!ImageUtil.isGifFile((new File(localImagePath)))) {
            String scale = ImageUtil.saveNewImage(localImagePath, 1280, 1280);
            img = chatpath + ImageUtil.getFileName(localImagePath) + ".pic";
        }
        //上传图片
        LoadingDataUtilBlack.show(NotificationMessageEditActivity.this, ResStringUtil.getString(R.string.wrchatview_sending));
        PansoftCloudUtil.getCloudRes(img, new PansoftCloudUtil.UpLoadListener() {
            @Override
            public void getHttpUrl(Boolean isSuccess, String url) {
                if (isSuccess) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
                            && (isDestroyed() || isFinishing())) {
                        return;
                    }
                    sendMessage(url, iamgeTitle, webUrl, webTitle);
                } else {
                    LoadingDataUtilBlack.dismiss();
                    ToastUtil.showToast(NotificationMessageEditActivity.this, ResStringUtil.getString(R.string.wrchatview_image_upload_fail));
                }
            }
        });


    }

    private void sendMessage(String imageUrl, String iamgeTitle, String webUrl, String webTitle) {
        //    {"imageUrl":"",
//            "imageTitle":"标题",
//            "webUrl":"www.baidu.com",
//            "webTitle","":}
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("imageUrl", imageUrl);
            jsonObject.put("imageTitle", iamgeTitle);
            jsonObject.put("webUrl", webUrl);
            jsonObject.put("webTitle", webTitle);

            IMStruct002 imStruct002 = new IMStruct002();
            imStruct002.setBody(jsonObject.toString().getBytes("UTF-8"));
            imStruct002.setTime(System.currentTimeMillis());
            imStruct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(CHAT_USER_ID)));
            imStruct002.setToUserType(Byte.valueOf(chatType));
            imStruct002.setToUserId(Integer.parseInt(mToUserId));
            imStruct002.setMessageChildType(MessageChildTypeConstant.subtype_notification);
            JFMessageManager.getInstance().sendMessage(imStruct002);

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(etBottomTitle.getWindowToken(), 0);
            LoadingDataUtilBlack.dismiss();
            finish();

        } catch (Exception e) {
            LoadingDataUtilBlack.dismiss();
            e.printStackTrace();
        }
    }


}
